//
//  DataStatItem.swift
//  SitPosition
//
//  Created by apple on 2019/1/27.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation


/**
 * 统计项类型
 */
enum DataStatType : Int, CaseIterable {
    case ok=1           // 姿势正确
    case headSlant      // 头部倾斜
    case bodySlantL     // 身体左倾
    case bodySlantR     // 身体右倾
    case headSlantLow   // 低头
    // case headSlantRotate// 头部旋转
    case unknownSlant   // 未知错误姿态
    
    public var description: String {
        switch self {
        case .ok: return Strings.dataStatPoseOk
        case .headSlant: return Strings.dataStatPoseHeadSlant
        case .bodySlantL: return Strings.dataStatPoseBodySlantL
        case .bodySlantR: return Strings.dataStatPoseBodySlantR
        case .headSlantLow: return Strings.dataStatPoseHeadSlantLow
        // case .headSlantRotate: return Strings.dataStatPoseHeadSlantRotate
        case .unknownSlant: return Strings.poseTypeSlantUnknown
        }
    }
    
    public var flagColor: UIColor? {
        switch self {
        case .ok: return UIColor(hexString: "#8CA8FB", alpha: 1.0)
        case .headSlant: return UIColor(hexString: "#FB8CC8", alpha: 1.0)
        case .bodySlantL: return UIColor(hexString: "#D154F5", alpha: 1.0)
        case .bodySlantR: return UIColor(hexString: "#F55485", alpha: 1.0)
        case .headSlantLow: return UIColor(hexString: "#FFA853", alpha: 1.0)
        // case .headSlantRotate: return UIColor(hexString: "#28AAAC", alpha: 1.0)
        case .unknownSlant: return UIColor(hexString: "#8E8E93", alpha: 1.0)
        }
    }
}


/**
 * 统计项
 */
struct DataStatItem {
    
    let type: DataStatType      // 统计项名称
    let duration: TimeInterval  // 统计时长（单位：s）
    let percent: Float          // 占比：0 ~ 100
    
    var durationDisplayString: String {
        return duration.formatedTimeString
    }
    
    var percentDisplayString: String {
        return String(format: "%.1f%%", percent)
    }
}


/**
 * 从服务器拉回来的学习统计数据
 * 对应服务端接口：NetworkApi.statByDate
 */
struct DataStatCollection : Codable {
    
    private struct DataStatItem_ : Codable {
        let type: Int            // 姿态类型
        let durationTime: Int64? // 持续时间，单位毫秒
        let proportion: Float?   // 比例：0~1
        
        // 将服务器端的“姿态类型”整型值转换为DataStatType类型
        static func int2DataStatType(_ rawVale: Int) -> DataStatType? {
            switch rawVale {
            case 1:
                return DataStatType.ok
            case 2:
                return DataStatType.headSlant
            case 3:
                return DataStatType.bodySlantL
            case 4:
                return DataStatType.bodySlantR
            case 5:
                return DataStatType.headSlantLow
            // case 6:
            //    return DataStatType.headSlantRotate
            case 7:
                return DataStatType.unknownSlant
            default:
                return nil
            }
        }
    }
    
    private struct DataStatStatistics_ : Codable { // 统计信息
        let learningDuration: Int64?    // 学习时长，单位毫秒
    }
    
    private let content: [DataStatItem_]?
    private let statistics: DataStatStatistics_?
    
    // 桥接转换：DataStatItem_ -> DataStatItem
    // 获取学习统计信息列表
    public func bridge2DataStatItem() -> [DataStatItem]? {
        guard let content_ = content else {
            return nil
        }
        var items: [DataStatItem] = []
        for item_ in content_ {
            guard let type = DataStatItem_.int2DataStatType(item_.type) else {
                continue
            }
            let item = DataStatItem(type: type,
                                    duration: TimeInterval(item_.durationTime ?? 0)/1000.0,
                                    percent: (item_.proportion ?? 0.0)*100.0)
            items.append(item)
        }
        
        // 按照type对结果排序
        items.sort { (lhs, rhs) -> Bool in
            return lhs.type.rawValue > rhs.type.rawValue
        }
        
        // 输出结果的格式为顺序存储的n种type对应的DataStatItem列表，
        // 如果中间缺失了某个type对应的DataStatItem就手动添加一个。
        let types = DataStatType.allCases
        for (idx, type) in types.enumerated() {
            let item = items.first { (item) -> Bool in
                return item.type == type
            }
            if item == nil {
                let newItem = DataStatItem(type: type, duration: 0, percent: 0)
                items.insert(newItem, at: idx)
            }
        }
        return items.isEmpty ? nil:items
    }
    
    // 获取学习时长（单位：s）
    public func learningDuration() -> TimeInterval {
        return TimeInterval(statistics?.learningDuration ?? 0)/1000.0
    }
}
